/********************************************************************************
 * Copyright 2001 - 2015 Comit. All Rights Reserved.
 * 作者：RockeyCai
 * 日期：2015-8-20 17:35:05
 * 描述：瑜伽资源表的映射模型。(自动生成，代码模块1.0v)
 * *****************************************************************************/
//var utility = require('../../server/lib/Utility');
//var async = require('async');
//var _ = require('underscore');
//var GlobalError=require('../../server/lib/GlobalError');
//var ResultListData = require('../../server/lib/ResultListData');
//var ResultJson = require('../../server/lib/ResultJson');
module.exports = function(YOGA) {
  //var gooddriver_servicer_cloud = YOGA.app.dataSources.task;

   /**
   * 分页获取瑜伽资源表数据
   * @param req
   * @param res
   */
  YOGA.getPageList = function ( req, res) {
    var ID = req.params.ID || req.query.ID;
    if (ID == null || ID <= 0) {
      return GlobalError.throwError(0, res);
    }

    var pageIndex = req.params.pageIndex || 1;
    if (pageIndex == null || pageIndex <= 0) {
      return GlobalError.throwErrorMsg(1, res);
    }

    var pageSize = req.params.pageSize || 30;
    if (pageSize == null || pageSize <= 0) {
      return GlobalError.throwErrorMsg(1, res);
    }

    //查询条件
    var query = {
      where: {ID: ID},
      limit: pageSize,
      skip: pageSize * (pageIndex - 1),
      order: 'ID asc'
//      ,
//      include: {
//       relation: 'servicePortModel'
//      }
    };

    //获取瑜伽资源表数量
    YOGA.count(query.where, function (err, count) {

      if (err) {
        console.log(err);
        return GlobalError.throwErrorMsg(err, res);
      }

      //无数据时，直接返回
      if (count <= 0) {
        return ResultListData.ResultListData(res, null, count);
      }

      //获取列表
      YOGA.find(query, function (err, list) {
        if (err) {
          return GlobalError.throwErrorMsg(err, res);
        }
        return ResultListData.ResultListData(res, list, count);
      });
    });
  }


  /**
   * 获取瑜伽资源表数据
   * @param req
   * @param res
   */
  YOGA.findAll = function ( req, res) {

    var ID = req.params.ID || req.query.ID || (JSON.parse(req.query.JSON_MAP)).ID;
    if (ID == undefined || ID <= 0) {
      GlobalError.throwError(0, res);
    }
    var query = {
      //fields: {ID: true},
      //limit: 10},
      //where:{ ID : 0},
      //include: {
      // relation: 'basicOrganization', // include the owner object
      //  scope: { // further filter the owner object
      //    include: [
      //      // basicOrganization 包含 servicer 和 servicePortList 对象
      //      {
      //        relation: 'servicer',
      //        scope: {
      //          include: { //servicer 包含 servicePortList
      //            relation: 'servicePortList',
      //            scope: {
      //              where: {state: 1},
      //              order: 'id asc'
      //            }
      //          }
      //        }
      //      },
      //      'panoramaList'
      //    ]
      //  }
      //},
      order: 'ID asc'
    };
    //根据主健获取记录
    this.find(query, function (err, instance) {
      if (err) {
        return GlobalError.throwErrorMsg(err, res);
      }
      return ResultJson.ResultJson(res , instance == null ? [] : instance);
    });
  }


  /**
   * 根据ID删除瑜伽资源表数据
   * @param req
   * @param res
   */
  YOGA.delById = function (req,res){

    var ID = req.params.ID || req.query.ID || (JSON.parse(req.query.JSON_MAP)).ID;
    if (ID == undefined || ID <= 0) {
     return GlobalError.throwError(0, res);
    }
    //根据主健删除记录
    this.destroyById(ID , function(err){
    if(err){
        console.log(err);
        return GlobalError.throwErrorMsg(err, res);
    }
        return ResultJson.ResultJson(res , 1);
    });
  }

  /**
   * 根据ID获取瑜伽资源表数据
   * @param req
   * @param res
   */
  YOGA.findModelById = function (req,res){

    var ID = req.params.ID || req.query.ID || (JSON.parse(req.query.JSON_MAP)).ID;
    if (ID == undefined || ID <= 0) {
      return GlobalError.throwErrorMsg("ID必填", res);
    }
    //根据主健获取记录
    this.findById(ID , function(err , instance){
      if(err){
        return GlobalError.throwErrorMsg(err, res);
      }
      return ResultJson.ResultJson(res , instance == null ? [] : instance);
    });
  }

  /**
   * 添加瑜伽资源表对象
   * @param req
   * @param res
   */
  YOGA.addModel = function (req, res) {

    var TITLE = req.params.TITLE || req.query.TITLE;
    if (_.isEmpty(TITLE)) {
      return GlobalError.throwErrorMsg("TITLE标题必填", res);
    }
    var IMG = req.params.IMG || req.query.IMG;
    if (_.isEmpty(IMG)) {
      return GlobalError.throwErrorMsg("IMG图片必填", res);
    }
    var URL = req.params.URL || req.query.URL;
    if (_.isEmpty(URL)) {
      return GlobalError.throwErrorMsg("URLurl必填", res);
    }
    var PID = req.params.PID || req.query.PID;
    if (PID == undefined || PID <= 0) {
      return GlobalError.throwErrorMsg("PID父亲ID必填", res);
    }
    var TIME = req.params.TIME || req.query.TIME;
    if (_.isEmpty(TIME)) {
      return GlobalError.throwErrorMsg("TIME时间长度必填", res);
    }
    var model = {};
    model.ID = (new Date()).valueOf();//主健
    model.TITLE = TITLE;//标题
    model.IMG = IMG;//图片
    model.URL = URL;//url
    model.PID = PID;//父亲ID
    model.TIME = TIME;//时间长度
    //保存记录
    this.create(model , function(err, obj){
      if (err) {
        return GlobalError.throwErrorMsg(err, res);
      }
      return ResultJson.ResultJson(res, obj);
    });
  }

  var cheerio = require('cheerio');
  var superagent = require('superagent');

  YOGA.getDataYoga = function (req, res) {

    var list = new Array();

    superagent.get('http://www.soku.com/search_video/q_%E7%91%9C%E4%BC%BD')
        .end(function (err, sres) {
          if (err) {
            console.log(err)
          }

          var $ = cheerio.load(sres.text);

          var item_clearfix = $('[class="item clearfix"]');
          //获取标题
          var ugc_navList = item_clearfix.find('.ugc_nav ul li')
          ugc_navList.each(function (idx, element) {
            var title = $(element).find('a').attr('_log_internalpos');
            var item = {};

            item.TITLE = title;
            item.ID = idx + 1;

            list.push(item);
          });

          //获取项目
          $('.yearnav').find('span').each(function (idx, span) {

            var myIndex = $(span).attr('v_index');
            var item = list[idx];
            var items = new Array();
            $(span).find('a').each(function (idx, a) {
              var itemSub = {};

              itemSub.ID = (new Date()).valueOf();
              itemSub.TITLE = $(a).text();
              itemSub.PID = item.ID;
              //YOGA.findUrlInfo($ , idx , itemSub);
              YOGA.findUrlInfo($ ,myIndex , idx , itemSub);
              items.push(itemSub);
            });
            item.items = items;
          });
          //console.log(list);


          for(var index = 0 ; index < list.length ; index++){

            var model = list[index]
            //console.log(model)
            //if(model.TITLE.indexOf('蕙兰') == -1){
            //  continue;
            //}
            YOGA.create(model , function(err, obj){
              if (err) {
                //console.log(err);
              }
            });



            for(var i = 0 ; i < model.items.length ; i++){
              var modelItem = model.items[i]

              YOGA.create(modelItem , function(err, obj){
                if (err) {
                  //console.log(err);
                }
              });

              for(var j = 0 ; j < modelItem.items.length ; j++){
                var modelItemItem = modelItem.items[j]
                //console.log(modelItemItem)
                YOGA.create(modelItemItem , function(err, obj){
                  if (err) {
                    //console.log(err);
                  }
                });
              }
            }

          }
        });
  };


  YOGA.findUrlInfo = function($ , index ,idx, itemSub){


    var subItems = new Array();

    var clazzName = 'ugc_' + index + '_' + idx
    console.log(clazzName);
    //获取视频
    $('.T').find('div').each(function (idx, div) {

      var clazz = $(div).attr('class');
      console.log(clazz);
      if(clazz.indexOf(clazzName) > -1){
        //获取一个视频
        $(div).find('ul li').each(function(i , li){

          $(li).find('ul').each(function(ii , liUl){

            var v_link = $(liUl).find('.v_link');
            var href = v_link.find('a').attr('href');
            var _log_sid = v_link.find('a').attr('_log_sid');
            var v_thumb = $(liUl).find('.v_thumb img').attr('src');
            var v_time = $(liUl).find('.v_time .num').text();
            var v_title = $(liUl).find('.v_title a').attr('title');

            //http://v.youku.com/v_show/id_XMTI3NjY3OTQ2NA==.html?from=s1.8-1-1.1
            var item = {};

            var start = href.indexOf('/id_');
            var end = href.indexOf('.html');
            item.URL = 'http://player.youku.com/embed/' + href.substring(start + 4 , end);
            item.ID = _log_sid;
            item.IMG = v_thumb;
            item.TIME = v_time;
            item.TITLE = v_title;
            item.PID = itemSub.ID;

            subItems.push(item)

          });
        });
      }
    });
    itemSub.items = subItems;
  }


  YOGA.getModel = function() {

    var list = new Array();

    superagent.get('http://www.soku.com/search_video/q_%E7%91%9C%E4%BC%BD')
        .end(function (err, sres) {
          if (err) {
            console.log(err)
          }

          var $ = cheerio.load(sres.text);

          var item_clearfix = $('[class="item clearfix"]');
          //获取标题
          var ugc_navList = item_clearfix.find('.ugc_nav ul li')
          ugc_navList.each(function (idx, element) {

            var title = $(element).find('a').attr('_log_internalpos');
            var item = {};

            item.TITLE = title;
            item.ID = idx + 1;

            list.push(item);
          });

          //获取项目
          $('.yearnav').find('span').each(function (idx, span) {
            var myIndex = $(span).attr('v_index');
            if(myIndex == 5){

              var item = list[idx];
              var items = new Array();
              $(span).find('a').each(function (idx, a) {

                var itemSub = {};
                itemSub.ID = (new Date()).valueOf();
                itemSub.TITLE = $(a).text();
                console.log(itemSub.TITLE);
                itemSub.PID = item.ID;

                YOGA.findUrlInfo($ ,myIndex , idx , itemSub);

                items.push(itemSub);
              });
              item.items = items;
            }
          });
          //console.log(list);

          //for(var index = 0 ; index < list.length ; index++) {
          //
          //  var model = list[index]
          //  if (model.TITLE.indexOf('蕙兰') == -1) {
          //    continue;
          //  }
          //  console.log(model)
          //
          //  for(var i = 0 ; i < model.items.length ; i++){
          //    var modelItem = model.items[i]
          //    console.log(modelItem)
          //    //for(var j = 0 ; j < modelItem.items.length ; j++){
          //    //  var modelItemItem = modelItem.items[j]
          //    //  //console.log(modelItemItem)
          //    //
          //    //}
          //  }
          //
          //
          //}
        });
  };

}
